import React, { useState, useEffect, useRef } from "react";
import TopNav from "../components/TopNav"; // 引入公共组件
import { useStore } from "../stores/store.jsx"; // 引入全局状态
import { Outlet } from "react-router-dom"; // 用于渲染子路由内容
import { Form, Input, Button, message, Modal } from "antd"; // 引入 Modal
import "../assets/style/home.css"; // 样式文件
import { USER_TYPES } from "../utils/userUtils"; // 引入用户工具类
import Cookies from "js-cookie"; // 引入 js-cookie
import { AIChatApi } from "../api/ai";
import { CreateExpectationsApi } from "../api/jobSeeker"; // 引入创建求职期望的 API
import Typewriter from "../components/Typewriter";
import "../assets/style/ai.css";
import { PlusOutlined, MessageOutlined } from "@ant-design/icons";

const CHAT_HISTORY_KEY = (userId) => `chat_history_${userId}`;

const Home = () => {
  const { state, getUserInfo, dispatch } = useStore(); // 从 Store 获取用户信息
  const [isModalVisible, setIsModalVisible] = useState(false); // 控制模态框显示状态
  const [expectationForm] = Form.useForm(); // 创建表单实例
  const [isChatVisible, setIsChatVisible] = useState(false);
  const [chatMessages, setChatMessages] = useState([]);
  const [inputMessage, setInputMessage] = useState("");
  const [isAiTyping, setIsAiTyping] = useState(false);
  const [activeChat, setActiveChat] = useState("current");
  const [chatHistory, setChatHistory] = useState([]);
  const messagesEndRef = useRef(null);
  // 修改登录状态判断逻辑
  const isLoggedIn = !!Cookies.get("access_token");
  // 在消息历史记录加载时检查用户ID
  useEffect(() => {
    const loadChatHistory = () => {
      // 确保用户已登录且有用户信息
      if (state.userInfo && state.userInfo.id) {
        const savedHistory = localStorage.getItem(
          CHAT_HISTORY_KEY(state.userInfo.id)
        );
        if (savedHistory) {
          setChatHistory(JSON.parse(savedHistory));
        } else {
          setChatHistory([]); // 新用户初始化空历史记录
        }
      } else {
        setChatHistory([]); // 未登录用户显示空历史记录
      }
    };

    loadChatHistory();
  }, [state.userInfo]); // 依赖于用户信息的变化
  // 添加滚动方法
  const scrollToBottom = () => {
    window.scrollTo({
      top: document.documentElement.scrollHeight,
      behavior: "smooth",
    });
  };

  // 在消息更新时触发滚动
  useEffect(() => {
    if (chatMessages.length > 0 || isAiTyping) {
      scrollToBottom();
    }
  }, [chatMessages, isAiTyping]);

  // 加载历史对话
  useEffect(() => {
    const loadChatHistory = () => {
      const savedHistory = localStorage.getItem(CHAT_HISTORY_KEY);
      if (savedHistory) {
        setChatHistory(JSON.parse(savedHistory));
      }
    };

    loadChatHistory();
  }, []);

  // 检查用户信息中的 expectation 是否为 null
  useEffect(() => {
    const checkExpectation = async () => {
      if (state.userType === USER_TYPES.JOB_SEEKER) {
        if (state.userInfo.expectation == null) {
          setIsModalVisible(true); // 显示模态框
        } else {
          setIsModalVisible(false); // 确保模态框关闭
        }
      }
    };
    checkExpectation();
  }, [state.userInfo, getUserInfo]);
  useEffect(() => {
    // 检查 cookie 是否存在
    const checkLoginStatus = () => {
      const token = Cookies.get("access_token");
      if (!token) {
        // 如果 cookie 不存在但状态中还有用户信息，清除状态
        dispatch({ type: "CLEAR_USER_INFO" });
      }
    };

    checkLoginStatus();
  }, [dispatch, state.userInfo]);
  // 提交求职期望
  const handleExpectationSubmit = async (values) => {
    try {
      const payload = {
        job_name: values.job_name,
        money: parseInt(values.money, 10), // 确保薪资为整数
        place: values.place,
        industry: values.industry,
      };
      console.log(payload);
      await CreateExpectationsApi(payload); // 调用创建求职期望的 API
      setIsModalVisible(false); // 关闭模态框

      await getUserInfo(true); // 重新获取用户信息
      message.success("求职期望创建成功");
    } catch (error) {
      console.error("创建求职期望失败", error);
      message.error("创建求职期望失败，请重试");
    }
  };

  // 处理发送消息
  const handleSendMessage = async () => {
    if (!inputMessage.trim() || !state.userInfo?.id) return;

    try {
      const userMessage = {
        type: "user",
        content: inputMessage,
      };

      const newMessages = [...chatMessages, userMessage];
      setChatMessages(newMessages);
      setInputMessage("");
      setIsAiTyping(true);

      const response = await AIChatApi(inputMessage);

      const aiMessage = {
        type: "ai",
        content: response.response,
      };

      const updatedMessages = [...newMessages, aiMessage];
      setChatMessages(updatedMessages);

      // 更新并保存历史记录
      if (activeChat === "current") {
        const newHistory = [
          {
            messages: updatedMessages,
            timestamp: new Date().toISOString(),
            preview:
              inputMessage.slice(0, 20) +
              (inputMessage.length > 20 ? "..." : ""),
            userId: state.userInfo.id,
          },
          ...chatHistory,
        ];

        setChatHistory(newHistory);
        localStorage.setItem(
          CHAT_HISTORY_KEY(state.userInfo.id),
          JSON.stringify(newHistory)
        );
      }
    } catch (error) {
      message.error("获取AI回复失败，请重试");
    } finally {
      setIsAiTyping(false);
    }
  };

  // 新建聊天方法
  const handleNewChat = () => {
    setChatMessages([
      {
        type: "ai",
        content: "您好！我是BOSS求职助手，请问有什么可以帮您的吗？",
      },
    ]);
    setActiveChat("current");
    setInputMessage(""); // 清空输入框
  };

  // 修改历史记录点击处理函数
  const handleHistoryClick = (index, chat) => {
    if (chat.userId === state.userInfo?.id) {
      setActiveChat(index);
      setChatMessages(chat.messages);
    }
  };

  return (
    <>
      <div>
        <TopNav /> {/* 使用公共组件 */}
        <main>
          {!isLoggedIn ? (
            <div className="video-container">
              {/* 视频内容 */}
              <video
                className="background-video"
                src="/video/loginBackground.mp4"
                autoPlay
                loop
                muted
              />
              <div className="overlay">
                <h1>欢迎来到来财职位网</h1>
                <p>找到属于你的职业机会</p>
              </div>
            </div>
          ) : (
            <div className="content">
              {/* 登录后的内容 */}
              <Outlet /> {/* 渲染子路由内容 */}
            </div>
          )}
        </main>
      </div>
      {/* 求职期望模态框 */}
      <Modal
        title="创建求职期望"
        open={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={null}
      >
        <Form form={expectationForm} onFinish={handleExpectationSubmit}>
          <Form.Item
            label="期望职位"
            name="job_name"
            rules={[{ required: true, message: "请输入期望职位" }]}
          >
            <Input placeholder="请输入期望职位" />
          </Form.Item>
          <Form.Item
            label="期望地点"
            name="place"
            rules={[{ required: true, message: "请输入期望地点" }]}
          >
            <Input placeholder="请输入期望地点" />
          </Form.Item>
          <Form.Item
            label="期望行业"
            name="industry"
            rules={[{ required: true, message: "请输入期望行业" }]}
          >
            <Input placeholder="请输入期望行业" />
          </Form.Item>
          <Form.Item
            label="期望薪资 (k/月)"
            name="money"
            rules={[
              { required: true, message: "请输入期望薪资" },
              { pattern: /^\d+$/, message: "薪资必须为数字" },
            ]}
          >
            <Input placeholder="请输入期望薪资" />
          </Form.Item>
          <Button type="primary" htmlType="submit" style={{ width: "100%" }}>
            提交
          </Button>
        </Form>
      </Modal>
      {isLoggedIn && (
        <>
          <div
            className="ai-chat-trigger"
            onClick={() => setIsChatVisible(true)}
          >
            <img src="/images/AI.png" alt="AI聊天" />
          </div>

          <Modal
            title={
              <div className="modal-title">
                <img src="/images/AI.png" alt="AI" className="title-avatar" />
                <span>BOSS求职助手</span>
              </div>
            }
            open={isChatVisible}
            onCancel={() => setIsChatVisible(false)}
            footer={null}
            width={1000}
            className="ai-chat-modal"
            centered
          >
            <div className="chat-layout">
              {/* 左侧边栏 */}
              <div className="chat-sidebar">
                <Button
                  type="primary"
                  icon={<PlusOutlined />}
                  onClick={handleNewChat}
                  className="new-chat-btn"
                >
                  新建对话
                </Button>

                <div className="chat-history">
                  <div className="history-title">历史对话</div>
                  {chatHistory.map((chat, index) => (
                    <div
                      key={index}
                      className={`history-item ${
                        activeChat === index ? "active" : ""
                      }`}
                      onClick={() => handleHistoryClick(index, chat)}
                    >
                      <MessageOutlined />
                      <span title={chat.preview}>
                        {chat.preview || `对话 ${chatHistory.length - index}`}
                      </span>
                    </div>
                  ))}
                </div>
              </div>

              {/* 右侧聊天区域 */}
              <div className="chat-main">
                <div className="chat-messages">
                  {chatMessages.map((msg, index) => (
                    <div key={index} className={`message-wrapper ${msg.type}`}>
                      {msg.type === "ai" ? (
                        <div className="ai-response">
                          <img
                            src="/images/AI.png"
                            alt="AI"
                            className="ai-avatar"
                          />
                          <div className="ai-content">
                            <Typewriter text={msg.content} speed={50} />
                          </div>
                        </div>
                      ) : (
                        <div className={`message ${msg.type}`}>
                          {msg.content}
                        </div>
                      )}
                    </div>
                  ))}
                  {isAiTyping && (
                    <div className="ai-response">
                      <img
                        src="/images/AI.png"
                        alt="AI"
                        className="ai-avatar"
                      />
                      <div className="ai-content">
                        <Typewriter loading={true} />
                      </div>
                    </div>
                  )}
                </div>

                <div className="chat-input-container">
                  <Input.TextArea
                    className="chat-input"
                    value={inputMessage}
                    onChange={(e) => setInputMessage(e.target.value)}
                    placeholder="输入您想问的问题..."
                    autoSize={{ minRows: 1, maxRows: 4 }}
                    onPressEnter={(e) => {
                      if (!e.shiftKey) {
                        e.preventDefault();
                        handleSendMessage();
                      }
                    }}
                  />
                  <Button
                    type="primary"
                    className="send-button"
                    onClick={handleSendMessage}
                    loading={isAiTyping}
                  >
                    发送
                  </Button>
                </div>
              </div>
            </div>
          </Modal>
        </>
      )}
    </>
  );
};

export default Home;
